package face.pay.open.user.service.impl;

import com.face.pay.SecurityConfig;
import com.face.pay.WxApiConfig;
import face.pay.constant.RoleCode;
import face.pay.constant.UserType;
import face.pay.dao.EnterpriseInfoDao;
import face.pay.dao.RoleInfoDao;
import face.pay.dao.UserInfoDao;
import face.pay.dao.UserRoleInfoDao;
import face.pay.entity.EnterpriseInfo;
import face.pay.entity.RoleInfo;
import face.pay.entity.UserInfo;
import face.pay.open.config.ApiConfigServer;
import face.pay.open.user.service.IApiUserRegService;
import face.pay.open.util.request.ApiRequestParam;
import face.pay.open.util.request.ErrorCode;
import face.pay.open.validate.ApiParamValidate;
import face.pay.util.ResultMessage;
import face.pay.util.bean.JavaBeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: zkj
 * @Date: 2019/8/29 11:17
 * @Description:
 */
@Service
@Slf4j
public class ApiUserRegServiceImpl implements IApiUserRegService {



    @Autowired
    private ApiParamValidate apiParamValidate;

    @Autowired
    private ApiConfigServer wxApiConfigServer;

    @Autowired
    private UserInfoDao userInfoDao;


    @Autowired
    private RoleInfoDao roleInfoDao;

    @Autowired
    private UserRoleInfoDao userRoleInfoDao;


    @Autowired
    private EnterpriseInfoDao enterpriseInfoDao;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage register(String json) {

        log.info("用户注册"+json);
        Integer code = ErrorCode.ERROR;

        String message  = "未知错误";

        Boolean flag= true;

        ApiRequestParam apiRequestParam  = apiParamValidate.parse(json);

        if(apiRequestParam!=null) {

            Integer oemId = apiRequestParam.getOemId();

            WxApiConfig config = wxApiConfigServer.getConfig(oemId);

            SecurityConfig securityConfig = config.getSecurityConfig();

            Map<String, String> data = apiRequestParam.getData();


            Boolean validate =  apiParamValidate.validate(data,apiRequestParam.getSign(),securityConfig);

            if(validate){

                UserInfo userInfo  = (UserInfo)JavaBeanUtils.mapToBean(data,UserInfo.class);

                userInfo.setType(UserType.ENTERPRISE);
                String userName = userInfo.getUserName().trim();

                /**
                 * 参数验证
                 * 暂时省略
                 */
                userInfo.setOemId(oemId);
                userInfo.setType(UserType.ENTERPRISE);
                userInfo.setDeleted(0);
                Integer agencyUserId = userInfo.getAgencyId();


                    Integer name_count =  this.userInfoDao.countByOemAndUserName(oemId,userInfo.getUserName());

                    if(name_count>0){

                        Integer phoneCount = this.userInfoDao.countByOemIdAndTypeAndPhone(oemId,UserType.ENTERPRISE,userInfo.getMobile(), userInfo.getDeleted());

                        if(phoneCount>0){

                            Boolean success =  this.registUserWithRole(RoleCode.ROLE_ENTERPRISE_MANAGER, userInfo);

                            if(success){

                                Map<String,Object> returnData = new HashMap<>();
                                returnData.put("userId",userInfo.getId());

                                return  ResultMessage.createSuccess("注册成功",returnData);

                            }

                        }else {
                            code = ErrorCode.AUTH_ERROR;
                            message="手机号码已经被占用";
                        }


                    }else {
                        code = ErrorCode.AUTH_ERROR;
                        message="用户名以存在";
                    }


            }else {
                code = ErrorCode.SING_ERROR;
                message = ErrorCode.SING_ERROR_MESSAGE;
            }

        }


        return ResultMessage.createFail(message).setErrorCode(code);
    }

    public  Boolean registUserWithRole(String roleCode, UserInfo userInfo){


        RoleInfo roleInfo =  this.roleInfoDao.getUserRoleByCode(roleCode);

        if(roleInfo!=null){

            Integer roleId = roleInfo.getId();
            /**
             * 指定默认密码
             */
            if(StringUtils.isBlank(userInfo.getPassWord())){
                userInfo.setPassWord("888888");
            }


            String passWord = new BCryptPasswordEncoder().encode(userInfo.getPassWord());

            String userName = userInfo.getUserName().trim();
            userInfo.setUserName(userName);
            userInfo.setPassWord(passWord);

            String userType = userInfo.getType();

            if(UserType.ENTERPRISE.equals(userType)){

                Integer agencyId = userInfo.getAgencyId();
                Integer recommendId= userInfo.getRecommendId();
                if(agencyId==null){
                    userInfo.setAgencyId(userInfo.getRecommendId());
                }
                if(recommendId==null){
                    userInfo.setRecommendId(userInfo.getAgencyId());
                }
            }

            this.userInfoDao.insert(userInfo);
            Integer userId = userInfo.getId();
            this.userRoleInfoDao.insert(userId,roleId);

            if(UserType.ENTERPRISE.equals(userType)){
                /**
                 * 绑定商家
                 */
                EnterpriseInfo enterpriseInfo =  new EnterpriseInfo();

                enterpriseInfo.setUserId(userId);
                enterpriseInfo.setOemId(userInfo.getOemId());
                this.enterpriseInfoDao.insert(enterpriseInfo);

            }

            return  true;
        }


        return  false;
    }



}
